package com.xpsoft.oa.workflow.event;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.api.model.OpenProcessInstance;

import com.xpsoft.core.util.AppUtil;
import com.xpsoft.oa.model.admin.AdminArticleSend;
import com.xpsoft.oa.model.flow.ProcessRun;
import com.xpsoft.oa.model.system.AppUser;
import com.xpsoft.oa.model.system.FileAttach;
import com.xpsoft.oa.service.admin.AdminArticleSendService;
import com.xpsoft.oa.service.flow.ProcessRunService;
import com.xpsoft.oa.service.system.FileAttachService;

public class AdminArticleSendFinishListener implements EventListener{
	private Log logger=LogFactory.getLog(AdminArticleSendFinishListener.class);
	@Override
	public void notify(EventListenerExecution execution) throws Exception {
		//获取表单参数
		OpenProcessInstance pi=execution.getProcessInstance();
		String title = (String)pi.getVariable("adminArticleSend.title");
		String keyword = (String)pi.getVariable("adminArticleSend.keyword");
		String abstractions = (String)pi.getVariable("adminArticleSend.abstractions");
		String attachIds = (String)pi.getVariable("adminArticleSend.attachIds");
		
		AdminArticleSendService adminArticleSendService = (AdminArticleSendService)AppUtil.getBean("adminArticleSendService");
		AdminArticleSend adminArticleSend = new AdminArticleSend();
		adminArticleSend.setTitle(title);
		adminArticleSend.setKeyword(keyword);
		adminArticleSend.setAbstractions(abstractions);
		adminArticleSend.setArtileNo(adminArticleSendService.getNewArticleNo());

		FileAttachService fileAttachService = (FileAttachService)AppUtil.getBean("fileAttachService");
		if(StringUtils.isNotBlank(attachIds)){
			Set<FileAttach> fileSet = new HashSet<FileAttach>();
			String fileIds[] = attachIds.split(",");
			adminArticleSend.getFileAttachs().clear();
			for(String fileId:fileIds){
				fileSet.add(fileAttachService.get(Long.valueOf(fileId)));
			}
			adminArticleSend.getFileAttachs().addAll(fileSet);
		}
		
		ProcessRunService processRunService=(ProcessRunService)AppUtil.getBean("processRunService");
		ProcessRun processRun=processRunService.getByExeId(pi.getId());
		adminArticleSend.setProcessRunId(processRun.getRunId());
		
		adminArticleSendService.save(adminArticleSend);
		
		
		//获取流程发起者对象
		AppUser flowStartUser=(AppUser)execution.getProcessInstance().getVariable("flowStartUser");
	
		//所有参与流程的都发消息
		AppUtil.sendSysShortMsg(execution.getProcessInstance().getId(), flowStartUser);
	}

}
